import MPanel from './MPanel';

import QGame from '../../Tools/QGame';
import {Backpack} from '../../Tools/QGame'
import BackpackGrid from './BackpackGrid';
import { ItemDat } from '../../Tools/QType';
const {ccclass, property} = cc._decorator;

@ccclass
export default class BackpackPanel extends MPanel {
    private grids:BackpackGrid[];
    private BackPack:Backpack;    
    private scrollView:cc.ScrollView;
    private gridParent:cc.Node;
    onLoad(){
        super.onLoad();        
        this.gridParent = this.node.getChildByName("view").getChildByName("content");
        this.grids = cc.find("view/content",this.node).getComponentsInChildren(BackpackGrid);                    
        this.BackPack = QGame.Instance.Backpack;
        this.scrollView = this.getComponent(cc.ScrollView);
        this.node.on("scroll-began",()=>{
            let event = new cc.Event.EventCustom("TipPanelHide",true);
            this.node.dispatchEvent(event);
        })
    }
   
    start(){
        super.start();
        if(this.grids.length<this.BackPack.length){
            let n = Math.ceil(this.BackPack.length/5)*5-this.grids.length; 
            for(let i=0;i<n;i++){
                let node = cc.instantiate(this.grids[0].node);
                node.parent = this.grids[0].node.parent;   
                this.grids.push(node.getComponent(BackpackGrid));    
            }
        }

        for(let i=0;i<this.BackPack.length;i++){
            let item = this.BackPack.getAt(i)
            this.grids[i].setData(item.ItemDat,item.count)
        }        
    }

    /** 背包显示时 */
    updateUI(){
        this.scrollView.scrollToTop(0)
    }

    updateOnceUI(item?:{ItemDat:ItemDat,count:number}){
        super.updateUI();
        if(!item)return;
        

        let node = cc.find("view/content/"+item.ItemDat.id,this.node);
        if(node){
            //修改物品数量
            let grid = node.getComponent(BackpackGrid);
            grid.setData(item.ItemDat,item.count);
        }else{
            //如果执行过Start
            if(this.isRunStart){
                //新增物品
                let node = this.gridParent.getChildByName("item");
                //找到一个空位置
                if(node){
                    node.getComponent(BackpackGrid).setData(item.ItemDat,item.count)
                }else{
                    //创建新的格子
                    for(let i=0;i<5;i++){
                        let node = cc.instantiate(this.grids[0].node);
                        node.parent = this.grids[0].node.parent;   
                        let tg = node.getComponent(BackpackGrid)
                        this.grids.push(tg);    
                        if(i==0){
                            tg.setData(item.ItemDat,item.count)
                        }else{
                            tg.setData(null,0)
                        }
                    }
                }
            }
        }        
    }


}
